package servlets;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import webservices.helper.Helper;
import control.ControlService;

/**
 * Servlet implementation class CourseManageServlet
 */
public class CourseManageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CourseManageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}
	
	private void processRequest(HttpServletRequest request, HttpServletResponse response){
		try{
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e){}
		
		String action = request.getParameter("action");
		String requestXML = Helper.paramStr("action", action);

		if ("add".equals(action) || "update".equals(action)){
			requestXML += Helper.paramStr("courseName", Helper.getParam(request, "courseName"));
			requestXML += Helper.paramStr("description", Helper.getParam(request, "description"));
			requestXML += Helper.paramStr("teacher", Helper.getParam(request, "teacher"));
		}
			
		if ("delete".equals(action) || "update".equals(action)){
			requestXML += Helper.paramStr("courseID", Helper.getParam(request, "courseID"));
		}
		
		String responseXML = new ControlService().Call("CourseManage", requestXML);
		
		try {
			NodeList responseList = Helper.getResponse(responseXML);
			
			String status = ((Element)responseList.item(0)).getAttribute("name");
			
			if ("fail".equals(status)){
				response.getWriter().write("{status: -1, error:'" + ((Element)responseList.item(0)).getAttribute("value")+"'}");
			}else{
				response.getWriter().write("{status: 0}");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
